<?php if(!class_exists("View", false)) exit("no direct access allowed");?><main class="container mx-auto px-4 pt-24 pb-16 flex">
    <?php include $_view_obj->compile("left_menu.html"); ?>

    <!-- 用户列表 -->
    <section class="mb-10 w-3/4 ml-4 bg-white rounded-xl shadow-sm p-4">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-dark">用户列表</h2>
            <div class="flex items-center space-x-4" id="user-info">
                <button class="btn btn-warning" disabled="true" id="add-user-button">用户不支持添加，用户可以直接使用手机号登录，在这里为用户授权</button>
            </div>
        </div>
        <!-- 新增滚动容器 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" id="select-all-users">
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            ID
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            真实姓名
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            所属部门
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            用户名
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            电话
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            邮箱
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            最后登录时间
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            最后登录IP
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            状态
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                </thead>
                <tbody id="user-list" class="bg-white divide-y divide-gray-200">
                    <!-- 用户数据将通过 JavaScript 动态添加 -->
                </tbody>
            </table>
        </div>
        <div class="flex justify-center mt-4" id="pagination">
            <!-- 分页按钮将通过 JavaScript 动态添加 -->
        </div>
    </section>

    <!-- 添加用户弹出框 -->
    <div id="add-user-modal" class="fixed inset-0 z-50 hidden bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white rounded-xl shadow-2xl p-8 w-96 relative">
            <span id="close-add-user-modal" class="absolute top-3 right-3 text-gray-600 hover:text-gray-800 cursor-pointer">
                <i class="fa fa-times"></i>
            </span>
            <h2 class="text-2xl font-bold text-dark mb-6 text-center">添加用户</h2>
            <form id="add-user-form">
                <div class="mb-6">
                    <label for="add-username" class="block text-sm font-medium text-gray-700 mb-1">用户昵称</label>
                    <input type="text" id="add-username" class="input-field w-full" required>
                </div>
                <div class="mb-6">
                    <label for="add-realname" class="block text-sm font-medium text-gray-700 mb-1">真实姓名</label>
                    <input type="text" id="add-realname" class="input-field w-full" required>
                </div>
                <div class="mb-6">
                    <label for="add-dept" class="block text-sm font-medium text-gray-700 mb-1">所属部门</label>
                    <select id="add-dept" class="input-field w-full">
                        <!-- 部门选项将通过 JavaScript 动态添加 -->
                    </select>
                </div>
                <div class="mb-6">
                    <label for="add-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                    <input type="email" id="add-email" class="input-field w-full">
                </div>
                <div class="mb-6">
                    <label for="add-mobile" class="block text-sm font-medium text-gray-700 mb-1">电话</label>
                    <input type="text" id="add-mobile" class="input-field w-full">
                </div>
                <div class="flex justify-center space-x-6">
                    <button type="button" id="cancel-add-user" class="btn-secondary">取消</button>
                    <button type="submit" id="submit-add-user" class="btn-primary">提交</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑用户弹出框 -->
    <div id="edit-user-modal" class="fixed inset-0 z-50 hidden bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white rounded-xl shadow-2xl p-8 w-1/2 relative"> <!-- 调整弹框宽度 -->
            <span id="close-edit-user-modal" class="absolute top-3 right-3 text-gray-600 hover:text-gray-800 cursor-pointer">
                <i class="fa fa-times"></i>
            </span>
            <h2 class="text-2xl font-bold text-dark mb-6 text-center">编辑用户</h2>
            <form id="edit-user-form">
                <input type="hidden" id="edit-user-id">
                <input type="hidden" id="edit-user-dept-id"> <!-- 新增隐藏输入框 -->
                <div class="mb-6">
                    <label for="edit-username" class="block text-sm font-medium text-gray-700 mb-1">用户昵称</label>
                    <input type="text" id="edit-username" class="input-field w-full" required>
                </div>
                <div class="mb-6">
                    <label for="edit-realname" class="block text-sm font-medium text-gray-700 mb-1">真实姓名</label>
                    <input type="text" id="edit-realname" class="input-field w-full" required>
                </div>
                <div class="mb-6">
                    <label for="app-category" class="block text-sm font-medium text-gray-700 mb-1">应用分类</label>
                    <div id="app-category-dropdown" class="relative">
                        <input type="text" id="app-category-display" class="input-field w-full" readonly>
                        <div id="app-category-options" class="absolute top-full left-0 right-0 bg-white border border-gray-300 rounded-lg mt-1 hidden max-h-48 overflow-y-auto">
                            <!-- 这里会通过 JavaScript 动态添加分类选项 -->
                        </div>
                    </div>
                </div>
                <div class="mb-6">
                    <label for="edit-email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                    <input type="email" id="edit-email" class="input-field w-full">
                </div>
                <div class="mb-6">
                    <label for="edit-mobile" class="block text-sm font-medium text-gray-700 mb-1">电话</label>
                    <input type="text" id="edit-mobile" class="input-field w-full">
                </div>
                <div class="mb-6">
                    <label for="permission-apps" class="block text-sm font-medium text-gray-700 mb-1">选择权限应用</label>
                    <div id="permission-apps-list" class="border border-gray-300 rounded-lg p-2 max-h-48 overflow-y-auto">
                        <!-- 权限应用列表将通过 JavaScript 动态添加 -->
                    </div>
                </div>
                <div class="flex justify-center space-x-6">
                    <button type="button" id="cancel-edit-user" class="btn-secondary">取消</button>
                    <button type="submit" id="submit-edit-user" class="btn-primary">提交</button>
                </div>
            </form>
        </div>
    </div>
</main>


<script>
    const itemsPerPage = 5;
    let currentPage = 1;
    let totalUsers = 0;

    // 获取部门列表
    function getDeptList() {
        const url = '<?php echo url(array('c'=>"system", 'a'=>"GetDeptList", ));?>';
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const depts = response.data;
                const addDeptSelect = $('#add-dept');
                const editDeptSelect = $('#edit-dept');
                addDeptSelect.empty();
                editDeptSelect.empty();
                depts.forEach(dept => {
                    const option = $('<option>');
                    option.val(dept.id);
                    option.text(dept.name);
                    addDeptSelect.append(option.clone());
                    editDeptSelect.append(option);
                });
            },
            error: function (error) {
                console.error('获取部门列表失败:', error);
            }
        });
    }

    // 显示用户列表
    function displayUsers() {
        const url = '<?php echo url(array('c'=>"system", 'a'=>"GetUserList", ));?>?start=' + currentPage + '&limit=' + itemsPerPage;

        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const users = response.data.list;
                totalUsers = response.data.pager.total_count;
                console.log(totalUsers);

                const userList = $('#user-list');
                userList.empty();

                users.forEach(user => {
                    const row = $('<tr>');
                    row.html(`
                        <td class="px-6 py-4 whitespace-nowrap">
                            <input id="${user.id}" type="checkbox">
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.realname}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.deptName}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.nickname}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.mobile}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.email}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.last}</td>
                        <td class="px-6 py-4 whitespace-nowrap">${user.ip}</td>
                        <td class="px-6 py-4 whitespace-nowrap ${user.status / 1 === 1 ? '' : 'text-danger'} ">
                            ${user.statusName}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button class="btn btn-info mr-2" onclick="editUser(${user.id})">编辑</button>
                            <button class="btn ${user.status / 1 === 1 ? 'btn-warning' : 'btn-info'} mr-2" onclick="toggleStatus(${user.id})">${user.status / 1 === 1 ? '禁用' : '启用'}</button>
                            <button class="btn btn-danger" onclick="deleteUser(${user.id})">删除</button>
                        </td>
                    `);
                    userList.append(row);
                });

                displayPagination();
            },
            error: function (error) {
                console.error('请求数据失败:', error);
            }
        });
    }

    // 显示分页导航
    function displayPagination() {
        const totalPages = Math.ceil(totalUsers / itemsPerPage);
        const pagination = $('#pagination');
        pagination.empty();

        const maxVisiblePages = 5; // 最大可见页码数
        const startPage = Math.max(currentPage - Math.floor(maxVisiblePages / 2), 1);
        const endPage = Math.min(startPage + maxVisiblePages - 1, totalPages);

        // 上一页按钮
        if (currentPage > 1) {
            const prevButton = $('<button>');
            prevButton.text('上一页');
            prevButton.addClass('px-3 py-1 mx-1 border rounded');
            prevButton.on('click', function () {
                currentPage--;
                displayUsers();
            });
            pagination.append(prevButton);
        }

        // 页码按钮
        for (let i = startPage; i <= endPage; i++) {
            const button = $('<button>');
            button.text(i);
            button.addClass('px-3 py-1 mx-1 border rounded');
            if (i === currentPage) {
                button.addClass('bg-primary text-white');
            }
            button.on('click', function () {
                currentPage = i;
                displayUsers();
            });
            pagination.append(button);
        }

        // 下一页按钮
        if (currentPage < totalPages) {
            const nextButton = $('<button>');
            nextButton.text('下一页');
            nextButton.addClass('px-3 py-1 mx-1 border rounded');
            nextButton.on('click', function () {
                currentPage++;
                displayUsers();
            });
            pagination.append(nextButton);
        }
    }

    // 打开添加用户弹出框
    const addUserButton = $('#add-user-button');
    const addUserModal = $('#add-user-modal');
    const closeAddUserModal = $('#close-add-user-modal');
    const cancelAddUser = $('#cancel-add-user');

    addUserButton.on('click', function () {
        addUserModal.removeClass('hidden');
    });

    closeAddUserModal.on('click', function () {
        addUserModal.addClass('hidden');
    });

    cancelAddUser.on('click', function () {
        addUserModal.addClass('hidden');
    });

    // 提交添加用户表单
    const addUserForm = $('#add-user-form');
    addUserForm.on('submit', function (e) {
        e.preventDefault();
        const username = $('#add-username').val();
        const realname = $('#add-realname').val();
        const dept = $('#add-dept').val();
        const email = $('#add-email').val();
        const mobile = $('#add-mobile').val();

        $.ajax({
            url: '<?php echo url(array('c'=>"system", 'a'=>"", ));?>',
            method: 'POST',
            data: {
                nickname: username,
                realname: realname,
                dept: dept,
                email: email,
                mobile: mobile
            },
            dataType: 'json',
            success: function (response) {
                addUserModal.addClass('hidden');
                displayUsers();
                addUserForm[0].reset();
            },
            error: function (error) {
                console.error('添加用户失败:', error);
            }
        });
    });

    // 从服务端接口获取应用分类数据
    function getAppCategories() {
        $.ajax({
            url: `<?php echo url(array('c'=>"system", 'a'=>"getDepts", ));?>`, // 替换为实际的接口地址
            method: 'GET',
            success: function (response) {
                const categoryOptions = $('#app-category-options');
                categoryOptions.empty();
                // 递归生成多级分类下拉列表
                function generateCategoryOptions(categories, level = 0) {
                    categories.forEach(category => {
                        const indent = '&nbsp;'.repeat(level * 4);
                        const option = `<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer" data-id="${category.id}">
                                            ${indent}${category.name}
                                        </div>`;
                        categoryOptions.append(option);
                        if (category.children && category.children.length > 0) {
                            generateCategoryOptions(category.children, level + 1);
                        }
                    });
                }
                generateCategoryOptions(response);
            },
            error: function (error) {
                alert('获取应用分类数据失败，请稍后重试。');
            }
        });
    }

    // 获取权限应用列表
    function getPermissionApps(uid) {
        const url = `<?php echo url(array('c'=>"system", 'a'=>"GetGroups", ));?>?uid=${uid}`; // 替换为实际的接口地址
        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const apps = response.data.groups;
                const roles = response.data.role.role.split(','); // 将返回的 role 字符串拆分为数组
                const permissionAppsList = $('#permission-apps-list');
                permissionAppsList.empty();
                apps.forEach(app => {
                    const checkbox = $('<input>').attr({
                        type: 'checkbox',
                        id: `permission-app-${app.role}`,
                        value: app.role
                    });
                    // 检查当前应用的 role 是否在返回的 roles 数组中，如果是则选中复选框
                    if (roles.includes(app.role)) {
                        checkbox.prop('checked', true);
                    }
                    const label = $('<label>').attr('for', `permission-app-${app.role}`).text(app.name);
                    const div = $('<div>').append(checkbox, label);
                    permissionAppsList.append(div);
                });
            },
            error: function (error) {
                console.error('获取权限应用列表失败:', error);
            }
        });
    }

    // 打开编辑用户弹出框
    function editUser(id) {
        const url = `<?php echo url(array('c'=>"system", 'a'=>"GetUser", ));?>?id=${id}`;

        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                const user = response.data;
                const editUserModal = $('#edit-user-modal');
                const editUserId = $('#edit-user-id');
                const editUsername = $('#edit-username');
                const editRealname = $('#edit-realname');
                const editDept = $('#app-category-display');
                const editEmail = $('#edit-email');
                const editMobile = $('#edit-mobile');

                editUserId.val(user.id);
                editUsername.val(user.nickname);
                editRealname.val(user.realname);
                editDept.val(user.dept);
                editEmail.val(user.email);
                editMobile.val(user.mobile);

                editUserModal.removeClass('hidden');

                // 获取应用分类数据
                getAppCategories();

                // 获取权限应用列表
                getPermissionApps(id);

                // 点击分类输入框，显示下拉框
                $('#app-category-display').on('click', function () {
                    $('#app-category-options').toggleClass('hidden');
                });

                // 点击下拉框中的分类选项，选择分类并隐藏下拉框
                $('#app-category-options').on('click', 'div', function () {
                    const selectedCategoryId = $(this).data('id');
                    const selectedCategoryName = $(this).text().trim();
                    $('#app-category-display').val(selectedCategoryName);
                    $('#edit-user-dept-id').val(selectedCategoryId); // 将所选分类的 ID 赋值给隐藏输入框
                    $('#app-category-options').addClass('hidden');
                });
            },
            error: function (error) {
                console.error('获取用户信息失败:', error);
            }
        });
    }

    // 关闭编辑用户弹出框
    const closeEditUserModal = $('#close-edit-user-modal');
    const cancelEditUser = $('#cancel-edit-user');

    closeEditUserModal.on('click', function () {
        const editUserModal = $('#edit-user-modal');
        editUserModal.addClass('hidden');
    });

    cancelEditUser.on('click', function () {
        const editUserModal = $('#edit-user-modal');
        editUserModal.addClass('hidden');
    });

    // 提交编辑用户表单
    const editUserForm = $('#edit-user-form');
    editUserForm.on('submit', function (e) {
        e.preventDefault();
        const id = parseInt($('#edit-user-id').val());
        const username = $('#edit-username').val();
        const realname = $('#edit-realname').val();
        const dept = $('#edit-user-dept-id').val(); // 从隐藏输入框中获取部门 ID
        const email = $('#edit-email').val();
        const mobile = $('#edit-mobile').val();
        const selectedApps = $('#permission-apps-list input:checked').map(function () {
            return $(this).val();
        }).get();
        const select_apps = selectedApps.join(',');

        $.ajax({
            url: '<?php echo url(array('c'=>"system", 'a'=>"UpdateUser", ));?>',
            method: 'POST',
            data: {
                uid: id,
                nickname: username,
                realname: realname,
                dept: dept,
                email: email,
                mobile: mobile,
                apps: select_apps
            },
            dataType: 'json',
            success: function (response) {
                const editUserModal = $('#edit-user-modal');
                editUserModal.addClass('hidden');
                displayUsers();
                editUserForm[0].reset();
            },
            error: function (error) {
                console.error('编辑用户失败:', error);
            }
        });
    });

    // 切换用户状态
    function toggleStatus(id) {
        $.ajax({
            url: `<?php echo url(array('c'=>"system", 'a'=>"UserDisable", ));?>?id=${id}`,
            method: 'PUT',
            dataType: 'json',
            success: function (response) {
                displayUsers();
            },
            error: function (error) {
                console.error('切换用户状态失败:', error);
            }
        });
    }

    // 删除用户
    function deleteUser(id) {
        if (confirm('确定要删除该用户吗？')) {
            $.ajax({
                url: `<?php echo url(array('c'=>"system", 'a'=>"UserDel", ));?>?id=${id}`,
                method: 'DELETE',
                dataType: 'json',
                success: function (response) {
                    displayUsers();
                },
                error: function (error) {
                    console.error('删除用户失败:', error);
                }
            });
        }
    }

    // 初始化显示用户列表和部门列表
    // getDeptList();
    displayUsers();
</script>